package com.yjd.comm.util;

import com.alibaba.fastjson.JSON;
import com.yjd.comm.rpm.RpmServiceKeyEnum;
import com.yjd.comm.sms.model.SmsRecordModel;
import com.yjd.comm.sms.service.ISmsRecordService;
import com.yjd.comm.system.model.SysParamModel;
import com.yjd.comm.system.util.SysParamUtil;
import com.yjd.comm.vo.Constant;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.log4j.Logger;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLDecoder;

/**
 * 短信发送工具类
 * Created by yangchangyan on 2017/6/27.
 */
public class SmsSenderUtils {
    private static Logger logger = Logger.getLogger(SmsSenderUtils.class);


    /**
     * @param mobile 手机号码，多个号码使用","分割
     * @param msg 短信内容
     * @return 返回值定义参见HTTP协议文档
     * @throws Exception
     */
    public static String smsSend(String mobile, String msg, String extno) throws Exception {

        // 获取发短信的配置信息
        SysParamModel sysParam = SysParamUtil.getSysParamModel(Constant.SysParamKeyEnum.SMS_CONFIG);
        if(null == sysParam){
            FrameUtil.throwBaseException1("获取短信发送配置失败");
        }

        Smsconfig config = JSON.parseObject(sysParam.getParam_value() ,Smsconfig.class);
        // 0:不会真实发送短信，1：真实发送短信到手机号
        if(0 == config.getSmsSwitch()){
            SmsSenderUtils.insertMsg(mobile, msg, "0", 0);
            return "0";
        }

        Long startTime = System.currentTimeMillis();
        HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
        GetMethod method = new GetMethod();
        try {
            URI base = new URI(config.getUrl(), false);
            method.setURI(new URI(base, "HttpBatchSendSM", false));
            method.setQueryString(new NameValuePair[]{
                    new NameValuePair("account", config.getAccount()),
                    new NameValuePair("pswd", config.getPswd()),
                    new NameValuePair("mobile", mobile),
                    new NameValuePair("needstatus", String.valueOf(config.isNeedstatus())),
                    new NameValuePair("msg", msg),
                    new NameValuePair("extno", extno),
            });
            int result = client.executeMethod(method);
            if (result == HttpStatus.SC_OK) {
                InputStream in = method.getResponseBodyAsStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                String decodeMsg = URLDecoder.decode(baos.toString(), "UTF-8");
                if(StringUtil.isEmpty(decodeMsg)){
                    logger.error("调用短信接口失败，返回为空");
                    FrameUtil.throwBaseException1("短信发送失败");
                }
                String[] msgs = decodeMsg.split(",");
                String status = msgs[msgs.length-1];
                SmsSenderUtils.insertMsg(mobile, msg, status, (System.currentTimeMillis() - startTime));

                return status;
            } else {
                throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
            }
        } finally {
            method.releaseConnection();
        }
    }

    public static void main(String[] args) throws Exception {
        Smsconfig sc = new Smsconfig();
       sc.setUrl("https://sapi.253.com/msg/HttpBatchSendSM");
       sc.setAccount("vipmfq06");
       sc.setPswd("Vipmfq06");
       sc.setSmsSwitch(1);
       sc.setNeedstatus(false);

        System.out.println(SmsSenderUtils.smsSend("1580633336","测试短信发送",""));
    }

    private static void insertMsg(final String mobile ,final String context,final String status, final long cost){
        ThreadPoolUtil.submitTask(new Runnable() {
            @Override
            public void run() {
                try{
                    getSmsRecordService().insert(new SmsRecordModel(mobile,context,Integer.parseInt(status), (int)cost,FrameUtil.getTime(null)));
                }catch (Exception e){
                    logger.error("短信记录入库失败，信息：moblie："+mobile+" context:"+context +" status:"+status+" 异常信息："+e);
                }
            }
        });
    }

    public static ISmsRecordService getSmsRecordService() {
        return ServiceHolder.getLocalService(ISmsRecordService.class,"smsRecordService");
    }

}


class Smsconfig{
    private String url; // url 应用地址，类似于http://ip:port/msg/
    private String account; // 账号
    private String pswd; // 密码
    private Integer smsSwitch; // 0:不会真实发送短信，1：真实发送短信到手机号
    private boolean needstatus; // 是否需要状态报告，需要true，不需要false

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPswd() {
        return pswd;
    }

    public void setPswd(String pswd) {
        this.pswd = pswd;
    }

    public Integer getSmsSwitch() {
        return smsSwitch;
    }

    public void setSmsSwitch(Integer smsSwitch) {
        this.smsSwitch = smsSwitch;
    }

    public boolean isNeedstatus() {
        return needstatus;
    }

    public void setNeedstatus(boolean needstatus) {
        this.needstatus = needstatus;
    }
}